﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HCFramework.API.LINQ;

namespace C
{
    public class UserRoleController
    {
        public static void Insert(UserRole a)
        {
            if (Get(a.UserID, a.RoleID) != null) return;

            HCDataContext db = new HCDataContext();
            db.UserRoles.InsertOnSubmit(a);
            db.SubmitChanges();
        }

        public static void Update(UserRole a, HCDataContext db)
        {
            db.SubmitChanges();
        }

        public static void Delete(int id)
        {
            HCDataContext db = new HCDataContext();
            UserRole a = db.UserRoles.Where(
                ik => ik.UserRoleID == id).First();
            if (a.Role.Name == RoleController.GetRegisterRoleName()) return;
            db.UserRoles.DeleteOnSubmit(a);
            db.SubmitChanges();
        }

        public static UserRole GetByID(int id, HCDataContext db)
        {
            return db.UserRoles.Where(
                ik => ik.UserRoleID == id).FirstOrDefault();
        }

        public static UserRole GetByID(int id)
        {
            return GetByID(id, new HCDataContext());
        }

        public static UserRole Get(int userID, int roleID)
        {
            return new HCDataContext().UserRoles.Where(
                ik => ik.UserID == userID && ik.RoleID == roleID).FirstOrDefault();
        }

        public static bool CanAccess(string username, string password, string trangName)
        {
            List<string> listUserRole = UserController.GetListRoleName(username, password);
            List<string> listTrangRole = TrangController.GetListRoleName(trangName);

            if (listUserRole.Intersect(listTrangRole).Count() > 0) return true;
            return false;
        }

        public static bool IsInRole(string username, string role)
        {
            HCDataContext dc = new HCDataContext();
            UserRole userRole = dc.UserRoles.Where(i => i.User.Username == username && i.Role.Name == role).FirstOrDefault();
            if (userRole == null)
            {
                return false;
            }
            return true;
        }
    }
}